#include "StdAfx.h"
#include ".\thread.h"
#include "ThreadPool.h"

CThread::CThread(void):m_hEvent(NULL),m_hthread(NULL),m_pthFun(NULL),m_bStoped(false),m_bAvailable(false),m_nSleep(0)
{
}


CThread::CThread(CThreadFunction *pfun):m_hEvent(NULL),m_hthread(NULL),m_pthFun(pfun),m_bStoped(false),m_bAvailable(false),m_nSleep(0){

}

CThread::~CThread(void)
{
	Stop();
}


bool CThread::Create(){
	return (m_hEvent = CreateEvent(0,TRUE,FALSE,NULL)) &&  
		(m_hthread = (HANDLE)_beginthreadex(NULL,0,TREEFUN,this,0,&m_thAddr));
}


bool CThread::SetFunction(CThreadFunction *pfun){
	return (m_pthFun=pfun) ? true : false;
}

bool CThread::Start(){
  return (TRUE==SetEvent(m_hEvent)) ? true :false;
  
}

void CThread::Stop(){
	m_bStoped=true;
	SetEvent(m_hEvent);
}


unsigned __stdcall CThread::TREEFUN( void * ptr){
	
	CThread *pth=(CThread *)ptr;
	while(true){
		if(NULL== pth  || pth->m_bStoped)
		   break;
		Sleep(pth->m_nSleep);
        pth->m_bAvailable=false;
        
		WaitForSingleObject(pth->m_hthread,INFINITE); 
		if (NULL== pth->m_pthFun)
			continue;

	    pth->m_pthFun->Run();
		pth->m_bAvailable=true;

	}
 
	if (pth!=NULL){
		pth->m_bAvailable=false;
		pth->m_pthFun=NULL;
		pth->m_bStoped=true;
		pth=NULL;
		
	}

  return 0;
}

